package com.android.Translator.View;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import com.android.Translator.R;
import com.android.Translator.Presenter.TranslatorPresenter;
import com.android.Translator.View.utils.ViewUtils;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils.TruncateAt;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher.ViewFactory;

public class LearnNewWord extends Activity{

	private TextView m_TextTimer;
    private Button      m_ButtonTranslate;
    private TextSwitcher m_TextWord;
    private ImageButton m_ImgPrevious, m_ImgNext;

    private CountDownTimer m_CoundownTimer;
    private static final String FORMAT = "%02d:%02d:%02d";
    private static boolean m_isWaiting = false;
    private static long m_SavedTimer;
    private static long m_TotalTimer;
    private long m_TimerUnit = 10000;
    //[Quan]list dung de test - thay the bang data myword
    private static ArrayList<String>  List_Example_Word;
    private static int curIndex = 0;
   
        @Override
        protected void onCreate(Bundle savedInstanceState) {
                // TODO Auto-generated method stub
                super.onCreate(savedInstanceState);
                setContentView(R.layout.learn_new_word);
                initView();
        }
       
        @Override
    	protected void onPause() {
    		// TODO Auto-generated method stub
    		super.onPause();
    		Log.i("LeanNewWord", "onPause");
    		m_CoundownTimer.cancel();
    	}


    	@Override
    	protected void onResume() {
    		// TODO Auto-generated method stub
    		super.onResume();
    		Log.i("LeanNewWord", "onResume");
    		//[Quan] -- resume countdown sau khi tro ve tu screen translate
    		if(m_isWaiting)
    			RefreshTimerCountDown();
    		//[Quan] -- end
    	}


    	@Override
    	protected void onStart() {
    		// TODO Auto-generated method stub
    		super.onStart();
    		Log.i("LeanNewWord", "onStart");
    		
    		Intent i = getIntent();
            Bundle bundel = i.getParcelableExtra("TIME_PACKAGE");
            m_TotalTimer = bundel.getInt("RATE_TIME")*m_TimerUnit;
            String GroupName = bundel.getString("GROUPNAME");
            showCountDownTimer();
            
    		List_Example_Word = new ArrayList<String>();
    		List_Example_Word = TranslatorPresenter.getMyWords(this, GroupName);
            setTextsToSwitcher(List_Example_Word);
    	}


    	@Override
    	protected void onStop() {
    		// TODO Auto-generated method stub
    		super.onStop();
    		m_TotalTimer = 0;
    		Log.i("LeanNewWord", "onStop");
    	}
    	@Override
    	protected void onRestart() {
    		// TODO Auto-generated method stub
    		super.onRestart();
    		Log.i("LeanNewWord", "onRestart");
    	}


    	@Override
    	public boolean onKeyDown(int keyCode, KeyEvent event) {
    		// TODO Auto-generated method stub
    		if (keyCode == KeyEvent.KEYCODE_BACK)
				ViewUtils.ShowAlertDialog(LearnNewWord.this, null,ViewUtils.ACTION_EXIT,
																getString(R.string.TITLE_ALERT_DIALOG), 
																getString(R.string.MESSAGE_ALERT_DIALOG));
    		return super.onKeyDown(keyCode, event);
    	}

		private void initView()
        {
                 m_TextTimer=(TextView)findViewById(R.id.textTimer);
                 m_ButtonTranslate = (Button) findViewById(R.id.LEARN_BTN_TRANSLATE);
                  
                 //[Quan] -- init TextSwitcher
                 m_TextWord = (TextSwitcher) findViewById(R.id.TextToLearn);
                 Animation slide_in_left = AnimationUtils.loadAnimation(this,
                  	   android.R.anim.fade_in);
					
				 m_TextWord.setInAnimation(slide_in_left);
					
				 m_TextWord.setFactory(new ViewFactory(){
					
					         @Override
					         public View makeView() {
					      	
					      	DisplayMetrics displaymetrics = new DisplayMetrics();
					      	getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
					     		
					     		int width = displaymetrics.widthPixels;
					     	    TextView TxtNewWord = new TextView(getApplicationContext());
					          TxtNewWord.setTextSize(50);
					          TxtNewWord.setTextColor(android.graphics.Color.BLACK);
					          TxtNewWord.setWidth(width/2);
					          //[Quan]-- cho word chay neu word qua dai
					          TxtNewWord.setSingleLine(true);
					          TxtNewWord.setEllipsize(TruncateAt.MARQUEE);
					          TxtNewWord.setSelected(true);
					          //end
					          TxtNewWord.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
					          TxtNewWord.setTypeface(Typeface.DEFAULT_BOLD);
					          return TxtNewWord;
					         }});
                 //[Quan] -- end init TextSwitcher
                 m_ImgPrevious = (ImageButton) findViewById(R.id.ImagePrevious);
                 m_ImgNext     = (ImageButton) findViewById(R.id.ImageNext);
                 m_ButtonTranslate.setOnClickListener(new OnClickListener() {
 					
 					@Override
 					public void onClick(View v) {
 						// TODO Auto-generated method stub
 						Intent i = new Intent(getApplicationContext(), TranslatorActivity.class);
 						Bundle bundle=new Bundle();
 						bundle.putString("KEY_WORD", List_Example_Word.get(curIndex));
 						i.putExtra("BUNDLE", bundle);
 						//[Quan] -- Dung countdown khi goi translate
 						m_CoundownTimer.cancel();
 						m_isWaiting = true;
 						//[Quan] -- END Cancel countdown
 						startActivity(i);
 					}
 				});
        }
       
        private void showCountDownTimer()
        {
        	//[Quan] neu count down dang tam dung thi tiep tuc
        	//voi thoi gian save
        	if (m_isWaiting)
        	{
        		m_TotalTimer = m_SavedTimer;
        		m_isWaiting = false;
        	}
        	//[Quan] -- end
        	
        	m_CoundownTimer = new CountDownTimer(m_TotalTimer, 1000) {

                        public void onTick(long millisUntilFinished) {

                        	//[Quan]Luu thoi gian count down
                        	m_SavedTimer = millisUntilFinished;
                        	//end
                        	
                        	//[Quan] -- khi thoi gian con 5s thi hien Button Translate
                        	if (millisUntilFinished < 5000)
                        		 m_ButtonTranslate.setVisibility(View.VISIBLE);
                        	//end
                        	
                                 m_TextTimer.setText(""+String.format(FORMAT,
                                 TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
                                 TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)- TimeUnit.HOURS.toMinutes(
                                 TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
                                 TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
                                 TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));            
                        }

                        public void onFinish() {
                        	//[Quan] Tu dong change word khac khi timer het thoi gian
                           if(curIndex == List_Example_Word.size()-1){
                               curIndex = 0;
                               m_TextWord.setText(List_Example_Word.get(curIndex));
                              }else{
                                  m_TextWord.setText(List_Example_Word.get(++curIndex));
                              }
                           //[Quan] - end
                           
                           m_ButtonTranslate.setVisibility(View.INVISIBLE);
                           //[Quan] khoi dong lai countdown
                           m_TotalTimer=10000;
                           RefreshTimerCountDown();
                           //[Quan] -- end
                        }
                     };
        	    m_CoundownTimer.start();          
        }
        
        
        /*
         * PUBLIC FUNCTIONS
         */
        
        protected void RefreshTimerCountDown() {
			// TODO Auto-generated method stub
        	m_CoundownTimer.cancel();
        	showCountDownTimer();
		}


		public void setTextsToSwitcher(final ArrayList<String> texts) {
            // TODO Auto-generated method stub
             m_TextWord.setText(texts.get(curIndex));

              m_ImgNext.setOnClickListener(new OnClickListener() {
                   
                    @Override
                    public void onClick(View v) {
                            // TODO Auto-generated method stub
                             if(curIndex == texts.size()-1)
                             {
                            	curIndex = 0;
	                            m_TextWord.setText(texts.get(curIndex));
                             }else
                             {
                                m_TextWord.setText(texts.get(++curIndex));
                             }
                            //[Quan] -- an nut translate khi nhan next
                             m_ButtonTranslate.setVisibility(View.INVISIBLE);
                           //[Quan] khoi dong lai countdown
                             RefreshTimerCountDown();
                             //[Quan] -- end
                    }
            });

              m_ImgPrevious.setOnClickListener(new OnClickListener() {
                           
                            @Override
                            public void onClick(View v) {
                                    // TODO Auto-generated method stub
                                    if (curIndex == 0)
                                            curIndex = texts.size();
                                     m_TextWord.setText(texts.get(--curIndex));
                                   //[Quan] -- an nut translate khi nhan previous
                                     m_ButtonTranslate.setVisibility(View.INVISIBLE);
                                   //[Quan] khoi dong lai countdown
                                     RefreshTimerCountDown();
                                     //[Quan] -- end
                            }
                    });
    }

}
